package com.smartHome.service.impl;

import com.smartHome.mapper.DeviceMapper;
import com.smartHome.mapper.SceneDeviceMapper;
import com.smartHome.mapper.SceneMapper;
import com.smartHome.pojo.dto.SceneDto;
import com.smartHome.pojo.entity.Device;
import com.smartHome.pojo.entity.Scene;
import com.smartHome.pojo.entity.SceneDevice;
import com.smartHome.service.SceneService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class SceneServiceImpl implements SceneService {

    @Autowired
    private SceneMapper sceneMapper;
    @Autowired
    private SceneDeviceMapper sceneDeviceMapper;
    @Autowired
    private DeviceMapper deviceMapper;

    @Override
    public List<Scene> getSceneList(Integer roomId) {
        List<Scene> sceneList=sceneMapper.getSceneList(roomId);
        return sceneList;
    }

    @Override
    public void updateScene(Scene scene) {
        sceneMapper.updateScene(scene);
    }

    @Override
    @Transactional
    public void implementUpdate(Integer sceneId) {
        List<SceneDevice> sceneDeviceList = sceneDeviceMapper.getSceneDeviceList(sceneId);
        for (SceneDevice sceneDevice:sceneDeviceList){
            deviceMapper.updateByScene(sceneDevice.getDeviceId(),sceneDevice.getStatus());
        }

    }

    @Override
    @Transactional
    public void addScene(Scene scene) {
        // 添加场景，执行完后scene对象的sceneId属性会被自动设置为新插入记录的ID
        sceneMapper.addScene(scene);
        
        // 现在可以直接使用scene.getSceneId()获取新插入的场景ID
        Integer sceneId = scene.getSceneId();
        
        // 添加场景设备数据
        // 1.通过房间Id查找所有设备列表
        List<Device> deviceList = deviceMapper.getDeviceList(scene.getRoomId());
        // 2.可以使用获取到的sceneId继续处理
        for (Device device : deviceList) {
            SceneDevice sceneDevice = new SceneDevice();
            sceneDevice.setSceneId(sceneId);  // 使用获取到的sceneId
            sceneDevice.setDeviceId(device.getDeviceId());
            sceneDevice.setDeviceName(device.getDeviceName());
            sceneDevice.setStatus(0);
            //添加场景设备数据
            sceneDeviceMapper.addSceneDevice(sceneDevice);
        }
    }

    @Override
    @Transactional
    public void deleteScene(Integer sceneId) {
        sceneMapper.deleteScene(sceneId);
        sceneDeviceMapper.deleteSceneDevice(sceneId);
    }

    @Override
    public List<Scene> getSceneNumber() {
        return sceneMapper.getSceneNumber();
    }


}
